import * as factory from "./factory.js"
import Project from "../models/projectModel.js"
import type { ParameterizedContext, Next } from "koa"
import multer from "multer"
import sharp from "sharp"
import util from "@mazp/util"

function verifySuffix(fileName: string) {
  let suffix = `(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)`
  let regular = new RegExp(`.*\.${suffix}`)
  return regular.test(fileName)
}

export const getAllProjects = factory.getAll(Project)
export const getProject = factory.getOne(Project)
export const createProject = async (ctx: ParameterizedContext, next: Next) => {
  let data = ctx.request.body
  let img = ctx.request.file
  if (Object.keys(data as Object).length === 0) {
    ctx.throw(404, "This is a bad request!")
  }
  // 校验图片，如果存在
  if (img) {
    // 验证图片
    if (!verifySuffix(img.originalname)) {
      ctx.throw(404, "please upload correct format img!")
    }
    // 保存图片
    ctx.state.fileName = `${util.randomChars(5)}-${Date.now()}.jpeg`
    await sharp(img.buffer)
      // .resize(500, 500)
      .toFormat('jpeg')
      .jpeg({ quality: 90 })
      .toFile(`imgs/${ctx.state.fileName}`)
  } else {
    ctx.state.fileName = `default.jpeg`
  }
  const doc = await Project.create(Object.assign(data as object, { img: ctx.state.fileName }));
  ctx.status = 200;
  ctx.body = {
    status: "success",
    data: { data: doc }
  }
}
export const updateProject = factory.UpdateOne(Project)
export const deleteProject = factory.deleteOne(Project)
